package com.enhe.gck.communal;

import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.CarbonEnumKeyValue;
import com.enhe.gck.CarbonRelationType;
import com.enhe.gck.item.OrderHWANE16677Item;
import com.enhe.gck.item.SupplyOrderHWANE16829Item;
import com.enhe.gck.item.SystemNumberHWANE18694Item;
import com.enhe.gck.item.WeighHWANE16720Item;
import com.enhe.gck.pojo.*;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kuangkie.carbon.common.AggregateVO;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.fg.DeleteMessageFactory;
import com.kuangkie.carbon.fg.FetchResultFactory;
import com.kuangkie.carbon.fg.ImproveResultFactory;
import com.kuangkie.carbon.fg.ops.ProRecordOpsBuilder;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.FGRecord;
import com.kuangkie.carbon.record.ProRecord;
import com.kuangkie.carbon.record.ProRecordBuilder;
import com.kuangkie.carbon.record.RecordQueryProConJunctionFactory;
import com.kuangkie.carbon.uid.model.UidManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
public class PublicMethod {

    public static void main(String[] args) {

    }
    /**
     * 返回信息
     */
    public static void returnMessage(ImproveResultFactory improveResultFactory,PublicReturn message){
        improveResultFactory.addRefuseMessage(message.getCode(),message.getName());
    }
    public static boolean returnMessageTrue(ImproveResultFactory improveResultFactory,PublicReturn message){
        improveResultFactory.addRefuseMessage(message.getCode(),message.getName());
        return true;
    }
    public static void returnMessage(ImproveResultFactory improveResultFactory,String message){
        improveResultFactory.addRefuseMessage("失败", message);
    }
    public static void returnMessage(DeleteMessageFactory defDeleteMessageFactory,PublicReturn message){
        defDeleteMessageFactory.addRefuseMessage(message.getCode(),message.getName());
    }
    public static void returnMessage(DeleteMessageFactory defDeleteMessageFactory,String message){
        defDeleteMessageFactory.addRefuseMessage("失败",message);
    }


    public static String createTimeStr(String header){
        return header+"_cd";
    }
    public static String updateTimeStr(String header){
        return header+"_ed";
    }

    public static String removeHeaderZero(String data,String split){
        StringBuffer info=new StringBuffer();
        if(split==null){
            info.append(data.replaceFirst("^0*", ""));
        }else {
            String[] dataList=data.split(split);
            for(int i=0;i<dataList.length;i++){
                info.append(dataList[i].replaceFirst("^0*", ""));
                if(i<dataList.length-1){
                    info.append(split);
                }
            }
        }
        return info.toString();
    }
    /**
     * 生成8位编码 且第四位为字符
     * @return
     */
    public static String getCharSelf8(){
        Random random = new Random();
        StringBuffer data=new StringBuffer();
        data.append(random.nextInt(90000000)+10000000);
        PublicEnum.Capital[] values=PublicEnum.Capital.values();
        int index=random.nextInt(values.length);
        data.replace(3,4,values[index].toString());
        return data.toString();
    }

    public static String getOrderCode(String header){
        return header+UidManager.getLongUID();
    }

    /**
     * 订单-header
     * @return
     */
    public static String getOrderCodeOR(){
        return PublicEnum.OrderHeader.OR.getCode()+getSystemNumber(PublicEnum.OrderHeader.OR.getCode());
    }
    /**
     * 供货-header
     * @return
     */
    public static String getOrderCodeSM(){
        return PublicEnum.OrderHeader.SM.getCode()+getSystemNumber(PublicEnum.OrderHeader.SM.getCode());
    }
    public static String getOrderCodeSMBig(){
        return PublicEnum.OrderHeader.SM.getCode()+UidManager.getLongUID16();
    }
    /**
     * 倒料-header
     * @return
     */
    public static String getOrderCodePM(){
        return PublicEnum.OrderHeader.PM.getCode()+getSystemNumber(PublicEnum.OrderHeader.PM.getCode());
    }
    /**
     * 充值-header
     * @return
     */
    public static String getOrderCodeRM(){
        return PublicEnum.OrderHeader.RM.getCode()+UidManager.getLongUID();
    }

    /**
     * 过磅-header
     * @return
     */
    public static String getOrderCodeWE(){
        return PublicEnum.OrderHeader.WE.getCode()+getSystemNumber(PublicEnum.OrderHeader.WE.getCode());
    }

    /**
     * FV-发票
     */
    public static String getOrderCodeFV(){
        return PublicEnum.OrderHeader.FV.getCode()+UidManager.getLongUID16();
    }

    public synchronized static String getSystemNumber(String type){
        LocalDate now = LocalDate.now();
        StringBuffer result=new StringBuffer();
        String date=getDateToString(now);
        result.append(getDateToString(now,PublicEnum.DateString.date3.getCode()));
        SystemNumber systemNumber=CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.系统单号_xtdh).getProConJunctionFactory()
                .addEqual(SystemNumberHWANE18694Item.基本属性组_日期,date)
                .addEqual(SystemNumberHWANE18694Item.基本属性组_类型,type)
                .goBack().queryABean(SystemNumber.class)
                ;
        if(systemNumber!=null){
            Integer count=systemNumber.getSum();

            int countSj=count+1;
            IntegrationMsg msg=CarbonPanel.getFGRecordBuilder(CarbonBaseConstant.系统单号_xtdh,systemNumber.getRecordCode())
                    .putAttribute(SystemNumberHWANE18694Item.基本属性组_总数,countSj).integrate();
            if (msg.success()){
                int countL=String.valueOf(countSj).length();
                if(countL>4){
                    result.append(countSj);
                }else {
                    for(int i=0;i<(5-countL);i++){
                        result.append("0");
                    }
                    result.append(countSj);
                }
            }else {
                log.info("修改单号数失败{}",msg.getRefuseMsgContentStr());
                result.append(UidManager.getLongUID16());
            }
        }else {
            IntegrationMsg msg=CarbonPanel.getFGRecordBuilder(CarbonBaseConstant.系统单号_xtdh)
                    .putAttribute(SystemNumberHWANE18694Item.基本属性组_日期,date)
                    .putAttribute(SystemNumberHWANE18694Item.基本属性组_类型,type)
                    .putAttribute(SystemNumberHWANE18694Item.基本属性组_总数,1).integrate();
            if (msg.success()){
                result.append("00001");
            }else {
                log.info("添加单号数失败{}",msg.getRefuseMsgContentStr());
                result.append(UidManager.getLongUID16());
            }
        }
        return result.toString();
    }

    public synchronized static String getToDayCount(String entity){
        String date=getDate(PublicEnum.DateString.date3.getCode());
        StringBuffer result=new StringBuffer();
        result.append(date);
        AggregateVO aggregateVO = CarbonPanel.getRecordQueryFactory(entity).getProConJunctionFactory()
                .addContain(createTimeStr(entity), getDate())
                .goBack().queryCount();
        if(aggregateVO!=null){
            int count = aggregateVO.getCount();
            int countL=String.valueOf(count).length();
            if(countL>4){
                result.append(++count);
            }else {
                for(int i=0;i<(5-countL);i++){
                    result.append("0");
                }
                result.append(++count);
            }
        }else {
            result.append("00001");
        }
        return result.toString();
    }
    public static BigDecimal addBigDecimal(Object o1, Object o2,Integer decimal,RoundingMode round){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        if(round==null){
            return o1b.add(o2b).setScale(decimal, RoundingMode.HALF_UP);
        }else {
            return o1b.add(o2b).setScale(decimal, round);
        }
    }

    public static BigDecimal subtractBigDecimal(Object o1, Object o2,Integer decimal,RoundingMode round){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        if(round==null){
            return o1b.subtract(o2b).setScale(decimal, RoundingMode.HALF_UP);
        }else {
            return o1b.subtract(o2b).setScale(decimal, round);
        }
    }
    public static BigDecimal multiplyBigDecimal(Object o1, Object o2,Integer decimal,RoundingMode round){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        if(round==null){
            return o1b.multiply(o2b).setScale(decimal, RoundingMode.HALF_UP);
        }else {
            return o1b.multiply(o2b).setScale(decimal, round);
        }
    }
    public static BigDecimal divideBigDecimal(Object o1, Object o2,Integer decimal,RoundingMode round){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        if(round==null){
            return o1b.divide(o2b,decimal,RoundingMode.HALF_UP);
        }else {
            return o1b.divide(o2b,decimal,round);
        }
    }

    public static BigDecimal addBigDecimal(Object o1, Object o2){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        return o1b.add(o2b);
    }

    public static BigDecimal subtractBigDecimal(Object o1, Object o2){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        return o1b.subtract(o2b);
    }
    public static BigDecimal multiplyBigDecimal(Object o1, Object o2){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        return o1b.multiply(o2b);
    }
    public static BigDecimal divideBigDecimal(Object o1, Object o2){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        return o1b.divide(o2b);
    }
    public static int compareToBigDecimal(Object o1, Object o2){
        BigDecimal o1b=new BigDecimal(o1.toString());
        BigDecimal o2b=new BigDecimal(o2.toString());
        return o1b.compareTo(o2b);
    }

    public static LocalDate getDateToLocalDate(Date date){
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
    public static LocalDateTime getDateToLocalDateTime(Date date){
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static String getDate(){
        LocalDate now = LocalDate.now();
        return getDateToString(now);
    }
    public static String getDate(String code){
        LocalDate now = LocalDate.now();
        return getDateToString(now, code);
    }
    public static String getDate(String code,Locale type){
        LocalDate now = LocalDate.now();
        return getDateToString(now, code,type);
    }
    public static String getDateToString(LocalDate localDate){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PublicEnum.DateString.date1.getCode());
        return localDate.format(formatter);
    }

    public static String getDateToString(LocalDate localDate,String code){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(code);
        return localDate.format(formatter);
    }
    public static String getDateToString(LocalDate localDate,String code,Locale type){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(code,type);
        return localDate.format(formatter);
    }

    public static String getDateTime(){
        LocalDateTime now = LocalDateTime.now();
        return getDateToStringTime(now);
    }
    public static String getDateTime(String code){
        LocalDateTime now = LocalDateTime.now();
        return getDateToStringTime(now, code);
    }
    public static String getDateToStringTime(LocalDateTime localDate){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PublicEnum.DateString.date11.getCode());
        return localDate.format(formatter);
    }

    public static String getDateToStringTime(LocalDateTime localDate,String code){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(code);
        return localDate.format(formatter);
    }


    public static PublicEntity.HttpResult post(String url,String jsonBody){
        PublicEntity.HttpResult info=new PublicEntity.HttpResult();
        try {
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
            request.setEntity(params);

            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);

            info.setOk(statusCode == 200);
            info.setData(responseBody);
            return info;
        }catch (Exception e){
            info.setOk(false);
            return info;
        }
    }

    /**
     * 获取第 okSum 次成功过磅信息
     * @param orderNumber 订单号
     */
    public static WeighOther getWeigh(String orderNumber, int okSum){
        return CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.过磅信息_gbxx).getProConJunctionFactory()
                .addEqual(WeighHWANE16720Item.基本属性组_订单号, orderNumber)
                .addEqual(WeighHWANE16720Item.基本属性组_是否正常,true)
                .addEqual(WeighHWANE16720Item.基本属性组_过磅次数,okSum)
                .goBack().queryABean(WeighOther.class);
    }
    public static FGRecord getWeighFg(String orderNumber, int okSum){
        return CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.过磅信息_gbxx).getProConJunctionFactory()
                .addEqual(WeighHWANE16720Item.基本属性组_订单号, orderNumber)
                .addEqual(WeighHWANE16720Item.基本属性组_是否正常,true)
                .addEqual(WeighHWANE16720Item.基本属性组_过磅次数,okSum)
                .goBack().queryARecord();
    }
    /**
     * add插入过磅信息
     */
    public static void saveWeigh(ImproveResultFactory improveResultFactory, String str1, BigDecimal big1, BigDecimal big2, BigDecimal big3, int int1, LocalDateTime ct){
        log.info("QAQ插入过磅信息】:{},{},{},{},{},{}",str1,big1,big2,big3,int1,ct);
        improveResultFactory.getProRecordOpsBuilder(CarbonBaseConstant.过磅信息_gbxx)
                .putAttribute(WeighHWANE16720Item.基本属性组_订单号,str1)
                .putAttribute(WeighHWANE16720Item.基本属性组_皮重,big1)
                .putAttribute(WeighHWANE16720Item.基本属性组_毛重,big2)
                .putAttribute(WeighHWANE16720Item.基本属性组_净重,big3)
                .putAttribute(WeighHWANE16720Item.基本属性组_过磅次数,int1)
                .putAttribute(WeighHWANE16720Item.基本属性组_是否正常,true)
                .putAttribute(WeighHWANE16720Item.基本属性组_过磅时间,ct)
        ;
    }
    public static void saveWeighAll(ImproveResultFactory improveResultFactory, String str1, BigDecimal big1, BigDecimal big2, BigDecimal big3, int int1, LocalDateTime ct, BigDecimal big21){
        log.info("QAQ插入过磅信息】:{},{},{},{},{},{}",str1,big1,big2,big3,int1,ct);
        improveResultFactory.getProRecordOpsBuilder(CarbonBaseConstant.过磅信息_gbxx)
                .putAttribute(WeighHWANE16720Item.基本属性组_订单号,str1)
                .putAttribute(WeighHWANE16720Item.基本属性组_皮重,big1)
                .putAttribute(WeighHWANE16720Item.基本属性组_毛重,big2)
                .putAttribute(WeighHWANE16720Item.基本属性组_实际过磅毛重,big21)
                .putAttribute(WeighHWANE16720Item.基本属性组_净重,big3)
                .putAttribute(WeighHWANE16720Item.基本属性组_过磅次数,int1)
                .putAttribute(WeighHWANE16720Item.基本属性组_是否正常,true)
                .putAttribute(WeighHWANE16720Item.基本属性组_过磅时间,ct)
        ;
    }

    /**
     * 获取当前数据库不存在的8位取货码
     */
    public static String getPickupCode(){
        String code=PublicMethod.getCharSelf8();
        List<String> codeOrder = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.订单记录_ddjl).getProConJunctionFactory()
                .addNotEqual(OrderHWANE16677Item.基本属性组_状态,PublicConstant.OrderStateOver)
                .addEqual(OrderHWANE16677Item.基本属性组_是否作废, CarbonEnumKeyValue.是否_否_f)
                .addEqual(OrderHWANE16677Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f)
                .addEqual(OrderHWANE16677Item.基本属性组_8位取货码, code)
                .goBack().queryCodes();

        List<String> codeSupplyOrder = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.供货订单_ghdd).getProConJunctionFactory()
                .addNotEqual(SupplyOrderHWANE16829Item.基本属性组_状态,PublicConstant.OrderStateOver)
                .addEqual(SupplyOrderHWANE16829Item.基本属性组_是否作废,CarbonEnumKeyValue.是否_否_f)
                .addEqual(SupplyOrderHWANE16829Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f)
                .addEqual(SupplyOrderHWANE16829Item.基本属性组_8位取货码, code)
                .goBack().queryCodes();
        while (codeOrder!=null&&!codeOrder.isEmpty()&&codeSupplyOrder!=null&&!codeSupplyOrder.isEmpty()){
            code=PublicMethod.getCharSelf8();
            codeOrder = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.订单记录_ddjl).getProConJunctionFactory()
                    .addNotEqual(OrderHWANE16677Item.基本属性组_状态,PublicConstant.OrderStateOver)
                    .addEqual(OrderHWANE16677Item.基本属性组_是否作废,CarbonEnumKeyValue.是否_否_f)
                    .addEqual(OrderHWANE16677Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f)
                    .addEqual(OrderHWANE16677Item.基本属性组_8位取货码, code)
                    .goBack().queryCodes();
            codeSupplyOrder = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.供货订单_ghdd).getProConJunctionFactory()
                    .addNotEqual(SupplyOrderHWANE16829Item.基本属性组_状态,PublicConstant.OrderStateOver)
                    .addEqual(SupplyOrderHWANE16829Item.基本属性组_是否作废,CarbonEnumKeyValue.是否_否_f)
                    .addEqual(SupplyOrderHWANE16829Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f)
                    .addEqual(SupplyOrderHWANE16829Item.基本属性组_8位取货码, code)
                    .goBack().queryCodes();
        }
        return code;
    }

    public static Cache<String,String> dataPermanent= Caffeine.newBuilder().build();

    /**
     *赋值 皮重毛中国
     * @param fetchResultFactory
     * @param weighOther 第一次过磅重量
     * @param weight 实际净重
     * @param pW 皮重code
     * @param mW 毛重code
     */
    public static void setPmWeight(Order order, FetchResultFactory fetchResultFactory, WeighOther weighOther, Double weight, String pW, String mW){
        BigDecimal weightTare=BigDecimal.ZERO;
        BigDecimal weightGross=BigDecimal.ZERO;
        String state=order.getState();
        if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待装卸货_dzxh).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_待过二磅_dgeb).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(state)
        ){
            weightTare= weighOther.getWeightTare()==null?BigDecimal.ZERO:BigDecimal.valueOf(weighOther.getWeightTare());

            fetchResultFactory.getRecordOpsBuilder().putAttribute(pW,weightTare);
            if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(state)
                    ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(state)){

                weightGross=weight==null?BigDecimal.ZERO:PublicMethod.addBigDecimal(weightTare,weight);
                fetchResultFactory.getRecordOpsBuilder().putAttribute(mW,weightGross);

                try {
                    WeighOther weighOther2 =PublicMethod.getWeigh(order.getOrder(),2);
                    BigDecimal sjjz=null;
                    BigDecimal sjmz=null;
                    if(weighOther2!=null){
                        if(weighOther2.getActualWeightGross()!=null){
                            sjjz=PublicMethod.subtractBigDecimal(weighOther2.getActualWeightGross(),weighOther.getWeightTare());
                            sjmz=weighOther2.getActualWeightGross();
                        }
                    }
                    if(sjjz==null){
                        sjjz=new BigDecimal(String.valueOf(order.getActualWeight()));
                    }
                    if(sjmz==null){
                        sjmz=weightGross;
                    }
                    fetchResultFactory.getRecordOpsBuilder()
                            .putAttribute(OrderHWANE16677Item.基本属性组_实际净重,sjjz)
                            .putAttribute(OrderHWANE16677Item.基本属性组_实际毛重,sjmz)
                    ;

                }catch (Exception e){}
            }
        }
    }
    public static void setPmWeightSub(String state, FetchResultFactory fetchResultFactory, WeighOther weighOther, Double weight, String pW, String mW){
        ProRecordOpsBuilder setData=fetchResultFactory.getRecordOpsBuilder();
        BigDecimal weightTare=BigDecimal.ZERO;
        BigDecimal weightGross=BigDecimal.ZERO;
        if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待装卸货_dzxh).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_待过二磅_dgeb).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(state)
                ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(state)
        ){
            weightGross= weighOther.getWeightGross()==null?BigDecimal.ZERO:BigDecimal.valueOf(weighOther.getWeightGross());

            setData.putAttribute(mW,weightGross);
            if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(state)
                    ||String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(state)){

                weightTare=(weight==null)?BigDecimal.ZERO:PublicMethod.subtractBigDecimal(weightGross,weight);

                setData.putAttribute(pW,weightTare);
            }
        }
    }

    public static RecordQueryProConJunctionFactory query(String entity){
        return CarbonPanel.getRecordQueryFactory(entity).getProConJunctionFactory();
    }

    /**
     * 获取数据
     * @param entityCode 模型id
     * @param id 数据id
     * @param cl 返回格式
     * @param <T>
     */
    public static <T> T getInfo(String entityCode,String id,Class<T> cl){
        return CarbonPanel.getRecordDiscover(entityCode).getRecordBean(id,cl,1);
    }
    public static <T> T getInfo(String entityCode,String id,Class<T> cl,int i){
        return CarbonPanel.getRecordDiscover(entityCode).getRecordBean(id,cl,i);
    }

    /**
     * new 对象 在integrate()；
     * @param entity
     * @param id
     * @return
     */
    public static ProRecordBuilder update(String entity,String id){
        return CarbonPanel.getProRecordBuilder(entity,id);
    }
    public static ProRecordOpsBuilder updateAny(ImproveResultFactory improveResultFactory,String entity,String id){
        return improveResultFactory.getProRecordOpsBuilder(entity,id);
    }
    /**
     * 新增修改时 插入其它表数据
     * @param entity
     * @return
     */
    public static ProRecordOpsBuilder saveAdd(ImproveResultFactory improveResultFactory,String entity){
        return improveResultFactory.getProRecordOpsBuilder(entity);
    }
    public static ProRecordOpsBuilder saveAddNow(ImproveResultFactory improveResultFactory){
        return improveResultFactory.getCurrentProRecordOpsBuilder();
    }

    /**
     * 体积=质量/密度
     * @param weight
     * @param p g/ml
     */
    public static BigDecimal getLiter(BigDecimal weight,BigDecimal p){
        if (weight==null||p==null||p.compareTo(BigDecimal.ZERO)<=0){
            return BigDecimal.ZERO;
        }
        return PublicMethod.divideBigDecimal(weight.multiply(new BigDecimal("1000")),p,PublicConstant.liter,null);
    }

    public static boolean validateDecimal(BigDecimal number,ImproveResultFactory improveResultFactory) {
        int scale = number.scale();
        if (scale > 2) {
            PublicMethod.returnMessage(improveResultFactory,PublicReturn.Input_2);
            return true;
        }
        return false;
    }
    public static boolean isStopCustomer(String is,ImproveResultFactory improveResultFactory){
        Customer customer=PublicMethod.getInfo(CarbonBaseConstant.客户管理_khgl, is, Customer.class);
        if(customer!=null&& customer.getIsStop()!=null&&customer.getIsStop()){
            PublicMethod.returnMessage(improveResultFactory,PublicReturn.Recharge_6);
            return true;
        }
        return false;
    }

    /**
     * 验证客户是否停用
     * @param type
     * @return
     */
    public static boolean verifyIsStopCustomer(ProRecord proRecord, ImproveResultFactory improveResultFactory,String type){
        boolean flag=false;
        try{
            switch (type) {
                case PublicConstant.OR:
                    Order order=proRecord.getBean(Order.class);
                    if(!(String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(order.getIsCancel())||
                            String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(order.getIsRefund()))){
                        if(String.valueOf(CarbonEnumKeyValue.是否_否_f).equals(order.getIsRetail())){
                            flag=isStopCustomer(proRecord.getGuestRecordCode(CarbonRelationType.RR_订单记录_客户名称_客户管理),improveResultFactory);
                        }else {
                            flag=isStopCustomer(proRecord.getGuestRecordCode(CarbonRelationType.RR_订单记录_散户_客户管理),improveResultFactory);
                        }
                    }
                    break;
                case PublicConstant.SM:
                    SupplyOrder supplyOrder=proRecord.getBean(SupplyOrder.class);
                    if(!(String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(supplyOrder.getIsCancel())||
                            String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(supplyOrder.getIsRefund()))){
                        flag=isStopCustomer(proRecord.getGuestRecordCode(CarbonRelationType.RR_供货订单_客户名称_客户管理),improveResultFactory);
                    }
                    break;
                case PublicConstant.RM:
                    Recharge recharge=proRecord.getBean(Recharge.class);
                    if(!(recharge.getIsCancel()!=null&&recharge.getIsCancel())){
                        flag=isStopCustomer(proRecord.getGuestRecordCode(CarbonRelationType.RR_充值记录_客户名称_客户管理),improveResultFactory);
                    }
                    break;
            }
            return flag;
        }catch (Exception e){
            log.info("异常{}",e.getMessage());
            return false;
        }
    }

    /**
     * 充值记录转map，外层map key：产品id，value：map key：单价，value：充值记录
     */
    public static Map<String, Map<BigDecimal, PublicEntity.RechargeUnit>> integration(List<Recharge> list){
        Map<String, Map<BigDecimal, PublicEntity.RechargeUnit>> map=new LinkedHashMap<>();
        list.forEach(r->{
            if(r!=null&&r.getUnivalence()!=null&&r.getUnivalence().getGoods()!=null){
                String goodId=r.getUnivalence().getGoods().getRecordCode();
                BigDecimal unit=new BigDecimal(String.valueOf(r.getUnivalence().getUnit()));
                if(map.containsKey(goodId)){
                    if(map.get(goodId).containsKey(unit)){
                        map.get(goodId).get(unit).getList().add(r);
                        BigDecimal availableBalanceSum=map.get(goodId).get(unit).getAvailableBalanceSum().add(new BigDecimal(String.valueOf(r.getAvailableBalance())));
                        map.get(goodId).get(unit).setAvailableBalanceSum(availableBalanceSum);
                    }else {
                        PublicEntity.RechargeUnit value=new PublicEntity.RechargeUnit();
                        List<Recharge> listR=new ArrayList<>();
                        listR.add(r);
                        value.setList(listR);
                        value.setAvailableBalanceSum(new BigDecimal(String.valueOf(r.getAvailableBalance())));
                        map.get(goodId).put(unit,value);
                    }
                }else {
                    Map<BigDecimal, PublicEntity.RechargeUnit> mapZ=new LinkedHashMap<>();
                    PublicEntity.RechargeUnit value=new PublicEntity.RechargeUnit();
                    List<Recharge> listR=new ArrayList<>();
                    listR.add(r);
                    value.setList(listR);
                    value.setAvailableBalanceSum(new BigDecimal(String.valueOf(r.getAvailableBalance())));
                    mapZ.put(unit,value);
                    map.put(goodId,mapZ);
                }
            }
        });
//        map.forEach((k,v)->{
//            v.forEach((k1,v1)->{
//                System.out.println("产品"+k+"单价"+k1+":"+v1);
//            });
//        });
        return map;
    }

    public static BigDecimal bigDecimalScale(BigDecimal value, int scale){
        return value.setScale(scale, RoundingMode.HALF_UP);
    }
}
